<template>
	<div :style="bj" align="center" class="xx">
		<!-- 登录的表单 -->
		<el-form  :rules="loginrules" :model="loginform"  ref="loginref" class="login_form" >
		  <el-form-item prop="username">
		    <el-input v-model="loginform.username" prefix-icon="el-icon-user" placeholder="请输入用户名"></el-input>
		  </el-form-item>
		  <el-form-item prop="password">
		    <el-input type="password" v-model="loginform.password" placeholder="请输入密码" show-password  prefix-icon="el-icon-lock"></el-input>
		  </el-form-item>
		  <!-- 登录 -->
		  <el-button type="primary" @click="submit">登录</el-button>
		  <!-- 重置输入信息 -->
		  <el-button type="info" @click="reset">重置</el-button>
		  <!-- 没有账号,用户注册 -->
		  <el-button type="warning"  @click="register">注册</el-button>
		  </el-form>
	</div>
</template>

<script>
	// 引入qs依赖
	import qs from "qs";
	export default{
		data(){
			return{
				bj: {
				  backgroundImage: "url(" + require("../img/19-麋鹿.jpeg") + ")",
				  backgroundRepeat: "no-repeat",
				  backgroundSize: '100%',
				  width:'100%',
				  height:'100%'
				  },
				loginform:{
					username:'',
					password:''
				},
				loginrules:{
						username:[
							{ required: true, message: '请输入用户名', trigger: 'blur' },
							{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
						],
						password:[
							{ required: true, message: '请输入密码', trigger: 'blur' },
							{ min: 6, max: 6, message: '长度在 6 个字符', trigger: 'blur' }
						]
					}
			}
		},
		methods:{
			// 登录按钮
			submit(){
				this.$refs.loginref.validate(async(val)=>{
					//如果格式验证正确，则val=true
					if(val){
						// 发送请求链接
						var res=await this.$http.post("login",qs.stringify(this.loginform));
						if(res.data.code==400){//错误
							this.$message.error(res.data.message);
						}else{
							this.$message.success(res.data.message);
							// 登录成功后，把当前用户的token放入本地
							window.sessionStorage.setItem("token",res.data.data.token)
							console.log(res.data)
							// 后端登录
							if(res.data.data.usertype==1){
								// 把当前登录的用户的编号放入到sessionStorge中
								window.sessionStorage.setItem("userid",res.data.data.userid)
								this.$router.push("/home");
							}else{//前端登录
								// 把当前登录的用户的编号放入到sessionStorge中
								window.sessionStorage.setItem("userid",res.data.data.userid)
								this.$router.push("/index");
							}
							
						}
						
					}else{
						this.$message.error('数据不合法，请检查')
					}
				})
			},
			// 重置按钮
			reset(){
				this.$refs.loginref.resetFields();
			},
			// 注册
			register(){
				this.$router.push("/register")
			}
		}
		
	}
</script>

<style scoped="scoped">

	.login_form{
		
		width: 300px;
		padding: 360px 100px 0px 100px;
		justify-content: center;
		align-items: center;
		height: 200px;
		
		margin: 0px auto;
		box-shadow: 0 8px 16px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
		border-radius: 10px;
		text-align: center;
	}
	.xx{
		width: 100%;
		height: 100%;
	}
</style>
